{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import mydataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_dl = mydataset.test_dl\n",
    "for xb,yb in test_dl:\n",
    "    print(xb.shape, yb.shape)\n",
    "    break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Pre-trained Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import mymodel"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = mymodel.model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "device = torch.device(\"cuda:3\" if torch.cuda.is_available() else \"cpu\")\n",
    "model = model.to(device)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def freeze_model(model):\n",
    "    for child in model.children():\n",
    "        for param in child.parameters():\n",
    "            param.requires_grad = False\n",
    "    print(\"model frozen\")\n",
    "    return model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = freeze_model(model)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "def deploy_model(model, test_dl):\n",
    "    y_pred = []\n",
    "    y_gt = []\n",
    "    with torch.no_grad():\n",
    "        for x,y in test_dl:\n",
    "            y_gt.append(y.item())\n",
    "            out = model(x.to(device)).cpu().numpy()\n",
    "            out = np.argmax(out, axis=1)[0]\n",
    "            y_pred.append(out)    \n",
    "    return y_pred, y_gt\n",
    "y_pred, y_gt = deploy_model(model,test_dl)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import accuracy_score\n",
    "acc=accuracy_score(y_pred,y_gt)\n",
    "print(\"accuracy: %.2f\" %acc)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## FGS Attach"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def perturb_input(xb, yb, model, alfa):\n",
    "    xb = xb.to(device)\n",
    "    xb.requires_grad = True\n",
    "    out = model(xb).cpu()\n",
    "    loss = F.nll_loss(out, yb)\n",
    "    model.zero_grad()\n",
    "    loss.backward()\n",
    "    xb_grad = xb.grad.data\n",
    "    xb_p = xb + alfa * xb_grad.sign()\n",
    "    xb_p = torch.clamp(xb_p, 0, 1)\n",
    "    return xb_p, out.detach()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from torchvision.transforms.functional import to_pil_image\n",
    "import torch.nn.functional as F\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline\n",
    "\n",
    "y_pred = []\n",
    "y_pred_p = []\n",
    "for xb,yb in test_dl:\n",
    "    xb_p, out = perturb_input(xb, yb, model, alfa = 0.005)\n",
    "    \n",
    "    with torch.no_grad():\n",
    "        pred = out.argmax(dim=1, keepdim=False).item()\n",
    "        y_pred.append(pred) \n",
    "        prob = torch.exp(out[:, 1])[0].item()\n",
    "\n",
    "        out_p = model(xb_p).cpu()\n",
    "        pred_p = out_p.argmax(dim=1, keepdim=False).item()\n",
    "        y_pred_p.append(pred_p)\n",
    "        prob_p = torch.exp(out_p[:, 1])[0].item()\n",
    "        \n",
    "    plt.subplot(1, 2, 1)\n",
    "    plt.imshow(to_pil_image(xb[0].detach().cpu()))\n",
    "    plt.title(prob)\n",
    "    plt.subplot(1, 2, 2)\n",
    "    plt.imshow(to_pil_image(xb_p[0].detach().cpu()))\n",
    "    plt.title(prob_p)\n",
    "    plt.show()\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "acc=accuracy_score(y_pred,y_gt)\n",
    "print(\"accuracy: %.2f\" %acc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "acc=accuracy_score(y_pred_p,y_gt)\n",
    "print(\"accuracy: %.2f\" %acc)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
